package com.baseandroid.push;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;
import com.androidbase.utils.AndroidUtils;
import com.androidbase.webview.WebViewTbsActivity;
import com.baseandroid.config.Global;
import com.baseandroid.event.PaysuccessEvent;
import com.baseandroid.utils.NotificationUtils;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.DataListBean;
import com.qianbao.qianbaobusiness.ui.cashier.CashierDetailActivity;
import com.qianbao.qianbaobusiness.ui.home.HomeActivity;
import com.qianbao.qianbaobusiness.ui.push.PushMsgDetailActivity;
import com.qianbao.qianbaobusiness.ui.webview.SimpleWebViewActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.Random;

public class MyMessageReceiver extends MessageReceiver {
    // 消息接收部分的LOG_TAG
    public static final String REC_TAG = "receiver";

    private static final String CT_TEXT = "01";// 文本
    private static final String CT_URL = "02";// 地址URL
    private static final String CT_APP = "03";// APP界面
    private static final int FROM_JPUSH = 1;// 从通知栏打开页面
    private static final int FROM_APP = 2;// 从应用内部打开页面

    @Override
    public void onNotification(Context context, String title, String summary, Map<String, String> extraMap) {
        Log.e("MyMessageReceiver", "Receive notification, title: " + title + ", summary: " + summary + ", extraMap: " + extraMap);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            String id = "1";
            CharSequence name = "notification channel";
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            mNotificationManager.createNotificationChannel(mChannel);
            Intent i = context.getPackageManager()
                    .getLaunchIntentForPackage(context.getPackageName());
            int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
            i.setFlags(flags);
            int chanelId = (int) (System.currentTimeMillis() % 10000) + 1000;
            PendingIntent pi = PendingIntent.getActivity(context.getApplicationContext(), chanelId, i, PendingIntent.FLAG_CANCEL_CURRENT);
            Notification notification = new Notification.Builder(context).setChannelId(id)
                    .setContentTitle(title)
                    .setContentText(summary)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pi)
                    .setAutoCancel(true)
                    .build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(chanelId, notification);
        }
    }

    @Override
    public void onMessage(Context context, CPushMessage cPushMessage) {

        Log.e("MyMessageReceiver", "onMessage, messageId: " + cPushMessage.getMessageId() + ", title: " + cPushMessage
                .getTitle() + ", content:" + cPushMessage.getContent());
        Log.e("MyMessageReceiver", "onMessage, messageId: " + cPushMessage.getMessageId() + ", title: " + cPushMessage
                .getTitle() + ", content:" + cPushMessage.getContent());
        int notificationId = new Random().nextInt(1000) % (1000 - 25 + 1) + 25;
        NotificationUtils notificationUtils = new NotificationUtils(context);
        try {
            JSONObject json = new JSONObject(cPushMessage.getContent());
            Log.d(TAG, "Extra Json: " + json);
            String title = json.getString("title");
            String msg_title = json.optString("title");
            String contenttype = json.getString("contenttype");
            String messageNo = json.getString("messageno");
            String content = json.getString("content");
            if (TextUtils.equals(contenttype, CT_TEXT)) {
                int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
                Bundle b = new Bundle();
                b.putString("contenttype", contenttype);
                b.putString("messageNo", messageNo);// 消息编号
                b.putString("title", "消息"); // 标题栏文本
                b.putString("msg_title", title);// 消息标题
                b.putString("content", content);// 消息内容
                if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                        .getPackageName())) {
                    Intent i = context.getPackageManager()
                            .getLaunchIntentForPackage(context.getPackageName());
                    i.setFlags(flags);
                    b.putInt("open_flag", FROM_JPUSH);
                    i.putExtras(b);
                    notificationUtils.sendNotification(title, notificationId, i);
                } else {
                    b.putInt("open_flag", FROM_APP);
                    Intent intentJpushMsg = new Intent(context, PushMsgDetailActivity.class);
                    intentJpushMsg.putExtras(b);
                    intentJpushMsg.setFlags(flags);
                    notificationUtils.sendNotification(title, notificationId, intentJpushMsg);
                }

            } else if (TextUtils.equals(contenttype, CT_URL)) {
                int flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                Bundle b = new Bundle();
                b.putString("contenttype", contenttype);
                b.putString("title", "消息");
                b.putString("url", content);
                if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                        .getPackageName())) {
                    Intent i = context.getPackageManager()
                            .getLaunchIntentForPackage(context.getPackageName());
                    i.setFlags(flags);
                    b.putInt("open_flag", FROM_JPUSH);
                    i.putExtras(b);
                    notificationUtils.sendNotification(title, notificationId, i);
                } else {
                    b.putInt("open_flag", FROM_APP);
                    Intent intentOtherWeb = new Intent(context, SimpleWebViewActivity.class);
                    intentOtherWeb.setFlags(flags);
                    intentOtherWeb.putExtras(b);
                    intentOtherWeb.putExtra(WebViewTbsActivity.WEBVIEW_TITLE, b.getString("title"));
                    intentOtherWeb.putExtra(WebViewTbsActivity.WEBVIEW_URL, b.getString("url"));
                    notificationUtils.sendNotification(title, notificationId, intentOtherWeb);
                }
            } else if (TextUtils.equals(contenttype, CT_APP)) {// 跳转app内部页面
                if (!TextUtils.isEmpty(content)) {
                    if (content.contains("?")) {
                        String[] to = content.split("\\?");
                        String toWhere = to[0]; // merchant_detail
                        String param = to[1];   // merchantNo=M20160101100009
                        if (TextUtils.equals(toWhere, "order_detail")) {// 打开“订单详情”
                            // 举例：order_detail?orderNo=ORD2015080410000000000424
                            if (!TextUtils.isEmpty(param) && param.contains("orderNo=")) {
                                String orderno = param.split("orderNo=")[1];
                                int flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                                Bundle b = new Bundle();
                                b.putString("contenttype", contenttype);
                                b.putString("toWhere", "order_detail");
                                b.putString("orderno", orderno);
                                if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                        .getPackageName())) {
                                    Intent i = context.getPackageManager()
                                            .getLaunchIntentForPackage(context.getPackageName());
                                    i.setFlags(flags);
                                    b.putInt("open_flag", FROM_JPUSH);
                                    i.putExtras(b);
                                    notificationUtils.sendNotification(title, notificationId, i);
                                }
                            }
                        }
                    } else {
                        if (content.contains("order_list")) {// 打开“交易列表”
                            int flags = Intent.FLAG_ACTIVITY_NEW_TASK;
                            Bundle b = new Bundle();
                            b.putString("contenttype", contenttype);
                            b.putString("toWhere", "order_list");
                            if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                    .getPackageName())) {
                                Intent i = context.getPackageManager()
                                        .getLaunchIntentForPackage(context.getPackageName());
                                i.setFlags(flags);
                                b.putInt("open_flag", FROM_JPUSH);
                                i.putExtras(b);
                                notificationUtils.sendNotification(title, notificationId, i);
                            }
                        } else if (content.contains("index")) {// 打开“app首页”
                            int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
                            Bundle b = new Bundle();
                            b.putString("contenttype", contenttype);
                            b.putString("toWhere", "index");
                            if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                    .getPackageName())) {
                                Intent i = context.getPackageManager()
                                        .getLaunchIntentForPackage(context.getPackageName());
                                i.setFlags(flags);
                                b.putInt("open_flag", FROM_JPUSH);
                                i.putExtras(b);
                                notificationUtils.sendNotification(title, notificationId, i);
                            } else {
                                Intent intentHome = new Intent(context, HomeActivity.class);
                                if (b != null) {
                                    intentHome.putExtras(b);
                                }

                                intentHome.setFlags(flags);
                                notificationUtils.sendNotification(title, notificationId, intentHome);
                            }
                        } else if (content.contains("getOrderInfo")) {
                            int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP;
                            Bundle b = new Bundle();
                            String orderno = json.getString("orderno");
                            String merchantno = json.getString("merchantno");
                            b.putString("merchantNo", merchantno);
                            b.putString("orderNo", orderno);
                            if (!AndroidUtils.isAppRunning(AndroidUtils.getContext()
                                    .getPackageName())) {
                                Intent i = context.getPackageManager()
                                        .getLaunchIntentForPackage(context.getPackageName());
                                i.setFlags(flags);
                                b.putInt("open_flag", FROM_JPUSH);
                                i.putExtras(b);
                                notificationUtils.sendNotification(title, notificationId, i);
                            } else {
                                if (Global.getPushBillState()) {
                                    Intent intentTransaction = new Intent(context, CashierDetailActivity.class);
                                    if (b != null) {
                                        intentTransaction.putExtras(b);
                                    }
                                    /*--传递DataListBean数据--*/
                                    DataListBean dataListBean = new DataListBean();
                                    dataListBean.setMerchantNo(merchantno);
                                    dataListBean.setOrderNo(orderno);
                                    intentTransaction.putExtra("bean", dataListBean);
                                    intentTransaction.setFlags(flags);
                                    notificationUtils.sendNotification(title, notificationId, intentTransaction);
                                }
                            }
                        }
                    }
                    // 支付成功通知首页更新
                    EventBus.getDefault().post(new PaysuccessEvent());
                }
            }

            /*--后台服务进行统计、语音播报--*/
            String contentbt = json.getString("content");
            String paytime = json.optString("paytime");
            String titlebt = json.getString("title");
            String isvoice = json.getString("isvoice");
            String msgpushts = json.optString("msgpushts");
            String msgpushid = json.getString("msgpushid");
            String msgpushch = json.getString("msgpushch");
            Intent i = new Intent(context, PushDoneService.class);
            i.putExtra("isvoice", isvoice);
            i.putExtra("msg", titlebt);
            i.putExtra("msgpushts", msgpushts);
            i.putExtra("msgpushid", msgpushid);
            i.putExtra("msgpushch", msgpushch);
            i.putExtra("orderts", paytime);
            i.putExtra("localmills", System.currentTimeMillis() + "");
            context.startService(i);
        } catch (JSONException e) {
            Log.e(TAG, "Get message extra JSON error! " + e.toString());
        }

    }

    @Override
    public void onNotificationOpened(Context context, String title, String summary, String extraMap) {
        Log.e("MyMessageReceiver", "onNotificationOpened, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);

    }

    @Override
    protected void onNotificationClickedWithNoAction(Context context, String title, String summary, String extraMap) {
        Log.e("MyMessageReceiver", "onNotificationClickedWithNoAction, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap);
    }

    @Override
    protected void onNotificationReceivedInApp(Context context, String title, String summary, Map<String, String> extraMap, int openType, String openActivity, String openUrl) {
        Log.e("MyMessageReceiver", "onNotificationReceivedInApp, title: " + title + ", summary: " + summary + ", extraMap:" + extraMap + ", openType:" + openType + ", openActivity:" + openActivity + ", openUrl:" + openUrl);
    }

    @Override
    protected void onNotificationRemoved(Context context, String messageId) {
        Log.e("MyMessageReceiver", "onNotificationRemoved");
    }

}